//------------------------------------------------------------------------------
// <pcdd-entitiy>
//     彩票主流业务类库
//     会员操作记录业务对象
// </pcdd-entitiy>
//------------------------------------------------------------------------------ 

using CL.Enum.Common;
using CL.Game.DAL;
using CL.Game.Entity;
using CL.Json.Entity.WebAPI;
using CL.Tools.Common;
using CL.View.Entity.Game;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CL.Enum.Common.Type;
using CL.Coupons.BLL;
using CL.Entity.Json.WebAPI;

namespace CL.Game.BLL
{

    /// <summary>
    /// UsersRecordBLL 业务
    /// </summary>
    public class UsersRecordBLL
    {
        Log log = new Log("UsersRecordBLL");
        UsersRecordDAL dal = new UsersRecordDAL(DbConnectionEnum.CaileGame);

        /// <summary>
        /// 账户金币变化明细记录
        /// </summary>
        /// <returns></returns>
        public List<udv_UserAccountDetail> QueryUserAccountDetail(int UserID, int tradeType, string startTime, string endTime, int pageSize, int pageIndex, ref int recordCount, ref long SumMoneyAdd, ref long SumMoneySub, ref long SumReward)
        {
            return dal.QueryUserAccountDetail(UserID, tradeType, startTime, endTime, pageSize, pageIndex, ref recordCount, ref SumMoneyAdd, ref SumMoneySub, ref SumReward);
        }
        /// <summary>
        /// 交易记录列表
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="rowsPerPage"></param>
        /// <param name="userId"></param>
        /// <returns></returns>

        /// 统计报表
        /// 操作类型,0.充值 1.购彩消费 2.提现冻结 3.提现失败解冻 4.金豆兑换
        /// 5.中奖 11.用户撤单 12.系统撤单 13.追号撤单 14.投注失败退款 
        /// 15.出票失败退款 16.充值退款冻结 17.退款失败返回金额
        /// 备注：不允许查询当月的数据
        /// </summary>
        /// <param name="day"></param>
        /// <returns></returns>
        public List<udv_CheckingReportDetail> QueryCheckingReport(DateTime dt)
        {
            List<udv_CheckingReportDetail> Results = new List<udv_CheckingReportDetail>();
            DateTime day_start = dt.AddDays(1 - dt.Day);
            DateTime day_end = dt.AddDays(1 - dt.Day).AddMonths(1).AddDays(-1);
            while (day_start.Day <= day_end.Day && day_start.Year == day_end.Year && day_start.Month == day_end.Month)
            {
                List<udv_CheckingReport> CheckingReports = dal.QueryCheckingReport(day_start.ToString("yyyy-MM-dd"));
                Results.Add(new udv_CheckingReportDetail()
                {
                    Day = day_start.ToString("yyyy-MM-dd"),
                    Pay = SetValues(CheckingReports, 0),
                    BuyLot = SetValues(CheckingReports, 1),
                    Freeze = SetValues(CheckingReports, 2),
                    UnFreeze = SetValues(CheckingReports, 3),
                    Imazamox = SetValues(CheckingReports, 4),
                    WinMoney = SetValues(CheckingReports, 5),
                    UserRevoke = SetValues(CheckingReports, 11),
                    SystemRevoke = SetValues(CheckingReports, 12),
                    ChaseRevoke = SetValues(CheckingReports, 13),
                    BetRevoke = SetValues(CheckingReports, 14),
                    TicketRevoke = SetValues(CheckingReports, 15),
                    RefundFreeze = SetValues(CheckingReports, 16),
                    RefundFailure = SetValues(CheckingReports, 17),
                    IsTotal = false
                });
                day_start = day_start.AddDays(1);
            }
            //合计
            Results.Add(new udv_CheckingReportDetail()
            {
                Day = "合计",
                Pay = Results.Sum(s => s.Pay),
                BuyLot = Results.Sum(s => s.BuyLot),
                Freeze = Results.Sum(s => s.Freeze),
                UnFreeze = Results.Sum(s => s.UnFreeze),
                Imazamox = Results.Sum(s => s.Imazamox),
                WinMoney = Results.Sum(s => s.WinMoney),
                UserRevoke = Results.Sum(s => s.UserRevoke),
                SystemRevoke = Results.Sum(s => s.SystemRevoke),
                ChaseRevoke = Results.Sum(s => s.ChaseRevoke),
                BetRevoke = Results.Sum(s => s.BetRevoke),
                TicketRevoke = Results.Sum(s => s.TicketRevoke),
                RefundFreeze = Results.Sum(s => s.RefundFreeze),
                RefundFailure = Results.Sum(s => s.RefundFailure),
                IsTotal = true
            });

            return Results;
        }
        public long SetValues(List<udv_CheckingReport> CheckingReports, int TradeType)
        {
            try
            {
                if (CheckingReports == null || CheckingReports.Count == 0)
                    return 0;
                var Entity = CheckingReports.Where(w => w.TradeType == TradeType).FirstOrDefault();
                if (Entity == null)
                    return 0;
                return Entity.TradeAmount;
            }
            catch (Exception ex)
            {
                log.Write(ex.ToString());
                return 0;
            }
        }
        /// <summary>
        /// 查询账户流水
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public List<udv_UsersRecord> QueryUsersRecordList(long UserID, int PageIndex, int PageSize, ref int RecordCount, ref int RecordWithdraw, ref int RecordBalance)
        {
            return dal.QueryUsersRecordList(UserID, PageIndex, PageSize, ref RecordCount, ref RecordWithdraw, ref RecordBalance);
        }
        /// <summary>
        /// 查询数据集
        /// </summary>
        /// <param name="UserID">用户编号</param>
        /// <param name="SchemeID">订单编号</param>
        /// <param name="TradeType">操作类型,0.充值 1.购彩消费 2.提现冻结 3.提现失败解冻 4.金豆兑换 5.中奖 11.用户撤单 
        /// 12.系统撤单 13.追号撤单 14.投注失败退款 15.出票失败退款 16.充值退款冻结 17.退款失败返回金额
        /// </param>
        /// <returns></returns>
        public UsersRecordEntity QueryEntitys(long UserID, long SchemeID, int TradeType)
        {
            return dal.QueryEntitys(UserID, SchemeID, TradeType);
        }
        /// <summary>
        /// 查询回水记录
        /// </summary>
        /// <returns></returns>
        public List<cv_UserRebate> QueryRebate(long UserID, int PageIndex, int PageSize, ref int RecordCount)
        {
            return dal.QueryRebate(UserID, PageIndex, PageSize, ref RecordCount);
        }


        #region 自定义方法


        /// <summary>
        /// 服务端回执处理方法
        /// </summary>
        /// <param name="OrderNo">订单号(数据库唯一编号)</param>
        /// <param name="RechargeNo">接口商交易号</param>
        /// <param name="PayType">交易类型</param>
        /// <param name="Amount">金额(接口返回的金额与之前存入数据库的金额对比)</param>
        /// <param name="OutRechargeNo">第三方交易号</param>
        /// <returns></returns>
        public bool PayInfo(string OrderNo, string RechargeNo, string PayType, long Amount, string OutRechargeNo)
        {
            try
            {
                string abbreviation = string.Empty;
                try
                {
                    abbreviation = Common.GetDescription((PaymentBank)System.Enum.Parse(typeof(PaymentBank), PayType, false));
                }
                catch
                {
                    abbreviation = PayType;
                }
                UsersPayDetailEntity entity = new UsersPayDetailBLL().QueryPayDetailsByOrderNo(OrderNo);
                if (!entity.Amount.Equals(Amount))
                    return false; //金额数据错误
                if (entity.Result == 1)
                    return true;
                entity.RechargeNo = RechargeNo;
                entity.OutRechargeNo = OutRechargeNo;
                entity.CompleteTime = DateTime.Now;
                entity.Result = 1;
                entity.PayType = abbreviation;
                var user = new UsersBLL().QueryEntityByUserCode(entity.UserID);
                user.Balance = user.Balance + Amount; //增加余额
                UsersRecordEntity account = new UsersRecordEntity()
                {
                    Balance = Amount,
                    CreateTime = DateTime.Now,
                    RelationID = OrderNo,
                    TradeAmount = Amount,
                    TradeRemark = abbreviation,
                    TradeType = 0,
                    UserID = entity.UserID
                };
                //事务处理
                bool result = dal.PayInfo(account, entity, user);
                if (result)
                {
                    #region redis数据更新
                    new UsersBLL().ModifyUserBalanceRedis(entity.UserID, Amount, true);
                    Task.Factory.StartNew(() =>
                    {
                        //变更静态数据
                        new UsersBLL().Staticdata_Recharge(true, Amount);
                        if (Amount >= 2000)
                            new UsersBLL().Staticdata_Largess(300);
                    });
                    #endregion
                    return true;
                }
                else
                    return false;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 用户交易记录
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="UserCode"></param>
        /// <param name="PageNumber"></param>
        /// <param name="RowsPerPage"></param>
        /// <returns></returns>
        public TradingResult UserTradingRecord(long UserCode, int PageNumber, int RowsPerPage)
        {
            TradingResult result = null;
            try
            {
                List<TradingEntity> arrayList = new List<TradingEntity>();
                int RecordCount = 0;
                int RecordWithdraw = 0;
                int RecordBalance = 0;
                var UsersRecordEntitys = this.QueryUsersRecordList(UserCode, PageNumber, RowsPerPage, ref RecordCount, ref RecordWithdraw, ref RecordBalance);
                if (UsersRecordEntitys != null)
                    arrayList = UsersRecordEntitys.Select(s => new TradingEntity()
                    {
                        UserCode = s.UserID,
                        Amount = s.TradeAmount,
                        Remark = s.remarks,
                        Time = s.CreateTime.ToString("yyyyMMddHHmmss")
                    }).ToList();
                #region 查询彩券
                long RecordCoupons = 0;
                var Coupons = new CouponsBLL().QueryCouponsPayment(UserCode, 1, 0);
                if (Coupons != null && Coupons.Count > 0)
                    RecordCoupons = Coupons.Sum(s => s.Balance);
                #endregion
                result = new TradingResult()
                {
                    Code = (int)ResultCode.Success,
                    Msg = Common.GetDescription(ResultCode.Success),
                    Balance = RecordBalance,
                    Withdraw = RecordWithdraw,
                    CouponsMoney = RecordCoupons,
                    Data = arrayList
                };
            }
            catch (Exception ex)
            {
                log.Write("用户交易记录错误[TradingRecord]：" + ex.StackTrace, true);
                result = new TradingResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }

        /// <summary>
        /// 会员回水
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        public UserRebateResult QueryRebate(long UserID, int PageIndex, int PageSize)
        {
            UserRebateResult result = null;
            try
            {
                int RecordCount = 0;
                int RecCode = (int)ResultCode.Success;
                List<UserRebate> Data = null;
                var Entitys = this.QueryRebate(UserID, PageIndex, PageSize, ref RecordCount);
                if (Entitys == null || Entitys.Count == 0)
                    RecCode = (int)ResultCode.NullData;
                else
                    Data = Entitys.Select(s => new UserRebate()
                    {
                        Rebate = s.TradeAmount,
                        RoomName = s.RoomName,
                        Time = s.CreateTime.ToString("yyyyMMddHHmmss")
                    }).ToList();
                result = new UserRebateResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode),
                    Count = RecordCount,
                    Data = RecCode != (int)ResultCode.Success ? null : Data
                };
            }
            catch (Exception ex)
            {
                result = new UserRebateResult()
                {
                    Code = (int)ResultCode.Error,
                    Msg = Common.GetDescription(ResultCode.Error),
                    Count = 0,
                    Data = null
                };
            }
            return result;
        }
        #endregion
    }
}
